(*DONT_TOUCH = "TRUE"*)
module bcc_cmd(
    input clk,
    input rst_n,

    input fun0_en, //全部开启
    input fun1_en, //全部关闭
    input fun2_en, //清零
    input fun3_en, //开始计数控制
    input fun4_en, //查询
    input stop_pluse, //来自于pid计数控制的停止脉冲信号

    input [31:0] count, //计数
    input [15:0] cmd_parameter , //命令参数

    output reg device_0, //电机
    output reg device_1, //电磁阀
    output reg clear_signal, //清空信号
    output reg pid_en //只有在计数需停止的时候才开启pid_en
    );

    //命令解析逻辑
    reg [15:0] cmd_param;
    reg is_count_flag; //是否在计数

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)begin
            is_count_flag <= 1'b0;
            device_0 <= 1'b0;
            device_1 <= 1'b0;
            clear_signal <= 1'b0;
            pid_en <= 1'b0;
        end
        else begin
            if (stop_pluse) begin //pid计数结束脉冲，与全部关闭一样，退出计数模式
                device_0 <= 1'b0;
                device_1 <= 1'b0;
                clear_signal <= 1'b0;
                is_count_flag <= 1'b0;
                pid_en <= 1'b0;
            end
            else if(fun0_en)begin //全部开启
                device_0 <= 1'b1;
                device_1 <= 1'b1;
                clear_signal <= 1'b0;
                is_count_flag <= 1'b0;
                pid_en <= 1'b0;
            end
            else if(fun1_en)begin //全部关闭
                device_0 <= 1'b0;
                device_1 <= 1'b0;
                clear_signal <= 1'b0;
                is_count_flag <= 1'b0;
                pid_en <= 1'b0;
            end
            else if(fun2_en)begin //刷新计数
                clear_signal <= 1'b1;
                is_count_flag <= 1'b0;
                pid_en <= 1'b0;
            end
            else if(fun3_en)begin //开始计数控制
                clear_signal <= 1'b1;
                cmd_param <= cmd_parameter; //寄存个数
                is_count_flag <= 1'b1;
                pid_en <= 1'b1;
            end
            else if(is_count_flag) begin //如果在计数，就对比当前颗粒来检查是否暂停
                if(count[15:0] < cmd_param)begin
                    is_count_flag <= 1'b1;
                    device_0 <= 1'b1;
                    device_1 <= 1'b1;
                    clear_signal <= 1'b0;
                    pid_en <= 1'b1;
                end
                else begin
                    is_count_flag <= 1'b0;
                    device_0 <= 1'b0;
                    device_1 <= 1'b0;
                    clear_signal <= 1'b0;
                    pid_en <= 1'b0;
                end
            end
            else begin
                is_count_flag <= is_count_flag;
                device_0 <= device_0;
                device_1 <= device_1;
                clear_signal <= 1'b0;
                pid_en <= pid_en;
            end  
        end
    end


endmodule
